<template>
  <div class="nav-bar">
    <div class="nav-container">
      <div class="logo-container" @click="goToHome">
        <img src="@/assets/logo.png" alt="AI学习辅助平台" class="logo" />
        <h1 class="site-name">AI学习辅助平台</h1>
      </div>
      
      <div class="nav-menu">
        <router-link :to="{ path: '/' }" class="nav-item" :class="{ active: isHomePage }">
          <span class="nav-text">首页</span>
        </router-link>
        <router-link :to="{ path: '/courses' }" class="nav-item" :class="{ active: isCoursesPage }">
          <span class="nav-text">课程</span>
        </router-link>
        <router-link :to="{ path: '/chat' }" class="nav-item" :class="{ active: isChatPage }">
          <span class="nav-text">AI助手</span>
        </router-link>
        <router-link :to="{ path: '/community' }" class="nav-item" :class="{ active: isCommunityPage }">
          <span class="nav-text">社区</span>
        </router-link>
      </div>
      
      <div class="search-container">
        <div class="search-wrapper" ref="searchWrapperRef">
          <el-input
            v-model="searchText"
            placeholder="搜索课程、题目或知识点"
            class="search-input"
            @keyup.enter="handleSearch"
            @focus="handleSearchFocus"
            @blur="handleSearchBlur"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
          
          <div 
            class="search-btn" 
            @click="handleSearch"
            :class="{ 'search-btn-active': isSearchActive }"
          >
            <el-icon><Search /></el-icon>
          </div>
          
          <!-- 搜索面板 -->
          <div class="search-panel" v-show="showSearchPanel" ref="searchPanelRef">
            <!-- 搜索历史 -->
            <div class="search-section">
              <div class="section-header">
                <h3>搜索历史</h3>
                <el-button type="text" @click="clearSearchHistory" class="clear-btn">清空</el-button>
              </div>
              <div class="history-list">
                <div 
                  v-for="(item, index) in searchHistory" 
                  :key="index" 
                  class="history-item"
                  @click="searchWithHistory(item)"
                  @mousedown.prevent
                >
                  <el-icon><Timer /></el-icon>
                  <span>{{ item }}</span>
                </div>
                <div v-if="searchHistory.length === 0" class="empty-history">
                  暂无搜索历史
                </div>
              </div>
            </div>
            
            <!-- 热门搜索 -->
            <div class="search-section">
              <div class="section-header">
                <h3>热门搜索</h3>
              </div>
              <div class="hot-search-list">
                <el-tag
                  v-for="(item, index) in hotSearches"
                  :key="index"
                  class="hot-search-item"
                  @click="searchWithHistory(item)"
                  @mousedown.prevent
                >
                  {{ item }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="nav-actions">
        <el-popover
          placement="bottom"
          :width="350"
          trigger="click"
          popper-class="message-popover"
          transition="el-zoom-in-top"
        >
          <template #reference>
            <div class="nav-icon message-icon" :class="{ 'has-unread': unreadMessagesCount > 0 }">
              <el-icon><Bell /></el-icon>
              <div v-if="unreadMessagesCount > 0" class="message-badge">{{ unreadMessagesCount }}</div>
            </div>
          </template>
          <div class="message-container">
            <el-tabs v-model="activeMessageTab">
              <el-tab-pane label="通知" name="notifications">
                <div class="message-list">
                  <div 
                    v-for="message in messages.notifications" 
                    :key="message.id" 
                    class="message-item"
                    :class="{ unread: !message.read }"
                    @click="markMessageRead('notifications', message.id)"
                  >
                    <div class="message-header">
                      <span class="message-title">{{ message.title }}</span>
                      <span class="message-time">{{ message.time }}</span>
                    </div>
                    <div class="message-content">{{ message.content }}</div>
                  </div>
                  <div v-if="messages.notifications.length === 0" class="empty-message">
                    暂无通知
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="系统消息" name="system">
                <div class="message-list">
                  <div 
                    v-for="message in messages.system" 
                    :key="message.id" 
                    class="message-item"
                    :class="{ unread: !message.read }"
                    @click="markMessageRead('system', message.id)"
                  >
                    <div class="message-header">
                      <span class="message-title">{{ message.title }}</span>
                      <span class="message-time">{{ message.time }}</span>
                    </div>
                    <div class="message-content">{{ message.content }}</div>
                  </div>
                  <div v-if="messages.system.length === 0" class="empty-message">
                    暂无系统消息
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div class="message-footer">
              <el-button type="primary" text @click="viewAllMessages">查看全部</el-button>
              <el-button type="primary" text @click="markAllMessagesRead">全部标为已读</el-button>
            </div>
          </div>
        </el-popover>
        
        <template v-if="isLoggedIn">
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-info">
              <span class="user-greeting">Hi，</span>
              <span class="username">{{ userInfo.nickName || userInfo.userName || '用户' }}</span>
              <el-avatar :src="userAvatar" :size="32" class="user-avatar">{{ userInitials }}</el-avatar>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>个人中心
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>设置
                </el-dropdown-item>
                <el-dropdown-item command="chat">
                  <el-icon><ChatDotRound /></el-icon>AI助手
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template v-else>
          <el-button type="primary" @click="login" class="login-btn">登录</el-button>
          <span class="divider">|</span>
          <el-button link @click="register" class="register-btn">注册</el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Search, Bell, Timer, User, Star, ArrowDown, Setting, 
  ChatDotRound, SwitchButton
} from '@element-plus/icons-vue';
import { getUserInfo } from '@/api/login';
import { getToken } from '@/utils/auth';

const router = useRouter();
const route = useRoute();
const store = useStore();
const searchText = ref('');
const showSearchPanel = ref(false);
const isSearchActive = ref(false);
const searchWrapperRef = ref(null);
const searchPanelRef = ref(null);
const activeMessageTab = ref('notifications');
const loading = ref(false);

// 热门搜索示例数据
const hotSearches = ref(['Python编程', '高等数学', '英语四级', '机器学习', '数据结构', 'Java基础']);

// 获取用户信息
const userInfo = computed(() => store.state.userInfo || {});
console.log('用户信息:', userInfo.value);
const isLoggedIn = computed(() => !!getToken());

// 用户头像处理
const userAvatar = computed(() => {
  if (userInfo.value && userInfo.value.avatar) {
    return userInfo.value.avatar;
  }
  return '';
});

// 如果没有头像，显示用户名首字母
const userInitials = computed(() => {
  const name = userInfo.value.nickName || userInfo.value.userName || '';
  return name.charAt(0).toUpperCase();
});

// 判断当前页面
const isHomePage = computed(() => route.path === '/');
const isCoursesPage = computed(() => route.path.startsWith('/courses'));
const isChatPage = computed(() => route.path.startsWith('/chat'));
const isCommunityPage = computed(() => route.path.startsWith('/community'));

// 获取消息数据
const messages = computed(() => store.state.home?.messages || { notifications: [], system: [] });
const unreadMessagesCount = computed(() => {
  let count = 0;
  if (messages.value.notifications) {
    count += messages.value.notifications.filter(msg => !msg.read).length;
  }
  if (messages.value.system) {
    count += messages.value.system.filter(msg => !msg.read).length;
  }
  return count;
});

// 获取搜索历史
const searchHistory = computed(() => store.state.home?.searchHistory || []);

// 导航到首页
const goToHome = () => {
  router.push('/');
};

// 处理搜索
const handleSearch = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索内容');
    return;
  }
  
  // 添加到搜索历史
  if (store.state.home && store.state.home.addSearchHistory) {
    store.dispatch('home/addSearchHistory', searchText.value.trim());
  }
  
  // 跳转到搜索结果页
  router.push({
    path: '/search',
    query: { q: searchText.value.trim() }
  });
  
  // 关闭搜索面板
  showSearchPanel.value = false;
};

// 处理搜索框聚焦
const handleSearchFocus = () => {
  showSearchPanel.value = true;
  isSearchActive.value = true;
};

// 处理搜索框失焦
const handleSearchBlur = () => {
  // 延迟关闭搜索面板，以便点击搜索历史项
  setTimeout(() => {
    if (!document.activeElement.closest('.search-wrapper')) {
      showSearchPanel.value = false;
      isSearchActive.value = false;
    }
  }, 200);
};

// 使用搜索历史项搜索
const searchWithHistory = (keyword) => {
  searchText.value = keyword;
  handleSearch();
};

// 清空搜索历史
const clearSearchHistory = () => {
  if (store.state.home && store.state.home.clearSearchHistory) {
    store.dispatch('home/clearSearchHistory');
  }
};

// 标记消息为已读
const markMessageRead = (type, id) => {
  if (store.state.home && store.state.home.markMessageRead) {
    store.dispatch('home/markMessageRead', { type, id });
  }
};

// 标记所有消息为已读
const markAllMessagesRead = () => {
  // 遍历所有类型的消息
  if (messages.value) {
    Object.keys(messages.value).forEach(type => {
      if (messages.value[type]) {
        messages.value[type].forEach(message => {
          if (!message.read) {
            markMessageRead(type, message.id);
          }
        });
      }
    });
  }
};

// 查看所有消息
const viewAllMessages = () => {
  router.push('/messages');
};

// 处理用户下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      store.dispatch('logout').then(() => {
        router.push('/login');
      });
    }).catch(() => {});
  } else if (command === 'profile') {
    router.push('/user/profile');
  } else if (command === 'settings') {
    router.push('/user/settings');
  } else if (command === 'chat') {
    router.push('/chat');
  }
};

// 登录
const login = () => {
  router.push('/login');
};

// 注册
const register = () => {
  router.push('/register');
};

// 从API获取用户信息
const fetchUserInfo = async () => {
  if (loading.value) return;
  
  loading.value = true;
  try {
    const res = await getUserInfo();
    if (res.code === 200) {
      store.commit('SET_USER_INFO', res.user);
      console.log('获取到用户信息:', res.user);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听登录状态变化
watch(() => isLoggedIn.value, (newVal) => {
  if (newVal) {
    fetchUserInfo();
  }
}, { immediate: true });

// 点击外部关闭搜索面板
const handleClickOutside = (event) => {
  if (searchWrapperRef.value && !searchWrapperRef.value.contains(event.target)) {
    showSearchPanel.value = false;
    isSearchActive.value = false;
  }
};

// 组件挂载时添加点击事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  
  // 如果已登录，获取用户信息
  if (isLoggedIn.value) {
    fetchUserInfo();
  }
});

// 组件卸载时移除点击事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style lang="scss" scoped>
.nav-bar {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  height: 60px;
  
  .nav-container {
    max-width: 1200px;
    margin: 0 auto;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 20px;
    
    .logo-container {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-right: 30px;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.02);
      }
      
      .logo {
        height: 36px;
        margin-right: 10px;
      }
      
      .site-name {
        font-size: 18px;
        font-weight: 600;
        color: #1e83ec;
        white-space: nowrap;
      }
    }
    
    .nav-menu {
      display: flex;
      margin-right: 20px;
      
      .nav-item {
        padding: 0 15px;
        font-size: 16px;
        color: #606266;
        text-decoration: none;
        position: relative;
        height: 60px;
        display: flex;
        align-items: center;
        transition: all 0.3s;
        
        .nav-text {
          position: relative;
          
          &::after {
            content: '';
            position: absolute;
            bottom: -4px;
            left: 0;
            width: 0;
            height: 2px;
            background-color: #1e83ec;
            transition: width 0.3s ease;
          }
        }
        
        &:hover, &.active {
          color: #1e83ec;
          
          .nav-text::after {
            width: 100%;
          }
        }
        
        &.active {
          font-weight: 500;
        }
      }
    }
    
    .search-container {
      flex: 1;
      max-width: 500px;
      margin: 0 20px;
      
      .search-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        
        .search-input {
          width: 100%;
          
          :deep(.el-input__wrapper) {
            border-radius: 20px;
            padding-right: 45px;
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            
            &.is-focus {
              box-shadow: 0 0 0 1px #1e83ec inset;
            }
          }
          
          :deep(.el-input__inner) {
            height: 40px;
            font-size: 14px;
          }
          
          .search-icon {
            color: #909399;
            font-size: 16px;
          }
        }
        
        .search-btn {
          position: absolute;
          right: 5px;
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background-color: #1e83ec;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;
          z-index: 2;
          
          &:hover {
            background-color: #1976d2;
            transform: scale(1.05);
          }
          
          &.search-btn-active {
            background-color: #1565c0;
            box-shadow: 0 2px 8px rgba(25, 118, 210, 0.5);
          }
        }
        
        .search-panel {
          position: absolute;
          top: 45px;
          left: 0;
          width: 100%;
          background-color: #fff;
          border-radius: 8px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
          z-index: 10;
          overflow: hidden;
          animation: slideDown 0.3s ease;
          
          .search-section {
            margin-bottom: 10px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .section-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 12px 15px;
              border-bottom: 1px solid #f0f2f5;
              
              h3 {
                margin: 0;
                font-size: 15px;
                color: #303133;
                font-weight: 500;
              }
              
              .clear-btn {
                color: #1e83ec;
                font-size: 13px;
                padding: 0;
                
                &:hover {
                  color: #1976d2;
                }
              }
            }
            
            .history-list {
              max-height: 200px;
              overflow-y: auto;
              
              .history-item {
                display: flex;
                align-items: center;
                padding: 10px 15px;
                cursor: pointer;
                transition: background-color 0.2s;
                
                &:hover {
                  background-color: #f5f7fa;
                }
                
                .el-icon {
                  margin-right: 10px;
                  color: #909399;
                }
              }
              
              .empty-history {
                padding: 20px;
                text-align: center;
                color: #909399;
                font-size: 14px;
              }
            }
            
            .hot-search-list {
              display: flex;
              flex-wrap: wrap;
              padding: 12px 15px;
              gap: 10px;
              
              .hot-search-item {
                cursor: pointer;
                transition: all 0.3s;
                background-color: #f0f7ff;
                border-color: #d9e9ff;
                color: #1e83ec;
                
                &:hover {
                  background-color: #e0f0ff;
                  transform: translateY(-1px);
                }
              }
            }
          }
        }
      }
    }
    
    .nav-actions {
      display: flex;
      align-items: center;
      
      .nav-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        cursor: pointer;
        transition: all 0.3s;
        position: relative;
        
        &:hover {
          background-color: #f5f7fa;
          transform: translateY(-1px);
        }
        
        &.has-unread {
          animation: pulse 2s infinite;
        }
        
        .message-badge {
          position: absolute;
          top: 0;
          right: 0;
          background-color: #f56c6c;
          color: #fff;
          font-size: 12px;
          min-width: 16px;
          height: 16px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 4px;
          animation: bounce 1s ease infinite;
        }
      }
      
      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: 20px;
        transition: all 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
          transform: translateY(-1px);
        }
        
        .user-greeting {
          font-size: 14px;
          color: #606266;
        }
        
        .username {
          margin: 0 8px;
          font-size: 14px;
          color: #1e83ec;
          font-weight: 500;
        }
        
        .user-avatar {
          background-color: #1e83ec;
          color: #fff;
          transition: transform 0.3s;
          
          &:hover {
            transform: scale(1.05);
          }
        }
      }
      
      .login-btn {
        background-color: #1e83ec;
        border-color: #1e83ec;
        border-radius: 20px;
        transition: all 0.3s;
        
        &:hover {
          background-color: #1976d2;
          border-color: #1976d2;
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(30, 131, 236, 0.3);
        }
      }
      
      .divider {
        margin: 0 8px;
        color: #dcdfe6;
      }
      
      .register-btn {
        color: #1e83ec;
        transition: all 0.3s;
        
        &:hover {
          color: #1976d2;
          transform: translateY(-1px);
        }
      }
    }
  }
}

// 动画效果
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

@keyframes bounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  
  .el-icon {
    margin-right: 8px;
  }
}

:deep(.message-popover) {
  padding: 0;
  border-radius: 8px;
  overflow: hidden;
  
  .message-container {
    .message-list {
      max-height: 300px;
      overflow-y: auto;
      
      .message-item {
        padding: 12px 15px;
        border-bottom: 1px solid #f0f2f5;
        cursor: pointer;
        transition: background-color 0.2s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.unread {
          background-color: #f0f7ff;
          
          &:hover {
            background-color: #e0f0ff;
          }
          
          .message-title {
            font-weight: 500;
          }
        }
        
        .message-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
          
          .message-title {
            font-size: 14px;
            color: #303133;
          }
          
          .message-time {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .message-content {
          font-size: 13px;
          color: #606266;
          line-height: 1.5;
        }
      }
      
      .empty-message {
        padding: 30px 0;
        text-align: center;
        color: #909399;
        font-size: 14px;
      }
    }
    
    .message-footer {
      display: flex;
      justify-content: space-between;
      padding: 10px 15px;
      border-top: 1px solid #f0f2f5;
      
      .el-button {
        font-size: 13px;
      }
    }
  }
}
</style> 